/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package cn.yitun.chat.yitunservercommonlib.util.codec;

import java.security.SecureRandom;
import java.util.UUID;

/**
 * 封装各种生成唯一性ID算法的工具类.
 * @author yitun
 * @version 2020-01-15
 */
public class IdGen {

	private static SecureRandom random = new SecureRandom();

	enum longNumTypeEnums {

		TIME_MILLIS(1, "毫秒"),

		TIME_NANO(2, "纳秒"),

		TIME_MILLIS_RANDOM_TAIL(3, "毫秒后加随机数尾巴"),

		;
		private int code;
		private String msg;

		longNumTypeEnums(int code, String msg) {
			this.code = code;
			this.msg = msg;
		}

		public int getCode() {
			return code;
		}

		public void setCode(int code) {
			this.code = code;
		}

		public String getMsg() {
			return msg;
		}

		public void setMsg(String msg) {
			this.msg = msg;
		}
	}
	
	/**
	 * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.
	 */
	public static String uuid() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
	
	/**
	 * 使用SecureRandom随机生成Long. 
	 */
	public static long randomLong() {
		return Math.abs(random.nextLong());
	}

	/**
	 * 基于Base62编码的SecureRandom随机生成bytes.
	 */
	public static String randomBase62(int length) {
		byte[] randomBytes = new byte[length];
		random.nextBytes(randomBytes);
		return Encodes.encodeBase62(randomBytes);
	}

	static Integer i = 0;
	/**
	 * 获取时间戳
	 * @param timeType 返回时间戳类型 1毫秒 2纳秒 3毫秒加随机数尾巴
	 * @return
	 */
	public static long getNumber(int timeType) {
		if (timeType == longNumTypeEnums.TIME_NANO.getCode())
			return System.nanoTime();
		else if (timeType == longNumTypeEnums.TIME_MILLIS.getCode())
			return System.currentTimeMillis();
		else if (timeType == longNumTypeEnums.TIME_MILLIS_RANDOM_TAIL.getCode()) {
			synchronized (i) {
				i++;
			}
			return System.currentTimeMillis() + i;
		}
		return System.currentTimeMillis();
	}

	/**
	 * 获取13位时间戳
	 */
	public static long getNumber() {
		return System.currentTimeMillis();
	}
	public static String getNumberStr() {
		return String.valueOf(getNumber());
	}

	static class NumberThread extends Thread {
		public void run() {
			for (int i = 0; i < 10; i++) {
				System.out.println(getNumber());
			}
		}
	}

	public static void main(String s[]) {
		for (int i = 0; i < 3; i++) {
			new NumberThread().start();
		}
	}

}
